<script setup>
import {ref, onMounted} from 'vue'
import api from '../api/orders_api.js'
import {ElMessage, ElMessageBox} from 'element-plus'
import { computed } from 'vue'
// ---------------------- 表格数据 ----------------------
const tableData = ref([])  // 存放订单数据
const total = ref(0)       // 总记录数

// ---------------------- 分页对象 ----------------------
const searchObj = ref({
  current: 1,
  limit: 10,
  buyerId: '',    // 支持按买家ID查询
  sellerId: ''    // 支持按卖家ID查询
})

// ---------------------- 加载订单 ----------------------
const loadOrders = async () => {
  try {
    const res = await api.page(searchObj.value)
    // 为每条记录计算总价
    const ordersWithTotal = (res.data || []).map(order => ({
      ...order,
      totalPrice: (Number(order.price) || 0) * (Number(order.quantity) || 0)
    }))
    tableData.value = ordersWithTotal
    total.value = res.count || 0
  } catch (error) {
    console.error(error)
    tableData.value = []
    total.value = 0
    ElMessage.error('加载订单失败')
  }
}

// ---------------------- 页面初始化 ----------------------
onMounted(async () => {
  await loadOrders()
})

//----------------------- 查询订单 ----------------------
const handleSearch = async () => {
  searchObj.value.current = 1;
  loadOrders()
}

//----------------------- 分页查询 ----------------------
const handleCurrentChange = (val) => {
  searchObj.value.current = val
  loadOrders()
}

//----------------------- 每页条数变化 ----------------------
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  searchObj.value.current = 1  // 每页条数变化也回到第一页
  loadOrders()
}

//----------------------- 删除订单 ----------------------
const handleDelete = async (orderId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？', '提示', {
      type: 'warning'
    })
    await api.del(orderId)   // 调用删除接口
    ElMessage.success('删除成功')
    loadOrders()             // 删除后刷新表格
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }
}

//----------------------- 修改订单 ----------------------
const editDialogVisible = ref(false)
const editForm = ref({})

// 打开编辑窗口
const handleEdit = (row) => {
  editForm.value = {...row}   // 拷贝一份当前行数据
  editDialogVisible.value = true
}
// 取消修改
const cancleEdit = () => {
  editForm.value = {}
  editDialogVisible.value = false
}
//提交修改
const submitEdit = async () => {
  try {
    const orderToEdit = {
      ...editForm.value,
      totalPrice: Number(editForm.value.price) * Number(editForm.value.quantity)
    }
    await api.edit(orderToEdit)  // 调用后端修改接口
    ElMessage.success('修改成功')
    editDialogVisible.value = false
    loadOrders()
  } catch (error) {
    console.error(error)
    ElMessage.error('修改失败')
  }
}


// ---------------------- 新增订单 ----------------------
const addWinVisible = ref(false)  // 新增弹窗是否显示
const newOrder = ref({})          // 新增订单表单

// 打开新增窗口
const showAddDialog = () => {
  newOrder.value = {
    buyerId: '',
    sellerId: '',
    productId: '',
    price: null,
    quantity: null
  }
  addWinVisible.value = true
}

// 取消新增
const addCancel = () => {
  newOrder.value = {}
  addWinVisible.value = false
}

// 提交新增
const addCommit = async () => {
  if (!newOrder.value.buyerId || !newOrder.value.sellerId || !newOrder.value.productId ||
      newOrder.value.price == null || newOrder.value.quantity == null) {
    ElMessage.warning('请填写完整订单信息')
    return
  }

  try {
    // 自动计算总价并传给后台
    const orderToAdd = {
      ...newOrder.value,
      totalPrice: Number(newOrder.value.price) * Number(newOrder.value.quantity)
    }
    await api.add(orderToAdd)

    ElMessage.success('新增成功')
    await loadOrders()        // 刷新表格
    addWinVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error('新增失败')
  }
}
// 计算属性：实时计算总价
const totalPrice = computed(() => {
  const price = Number(newOrder.value.price) || 0
  const quantity = Number(newOrder.value.quantity) || 0
  return price * quantity
})
</script>

<template>
  <div style="padding: 20px;">
    <h2>订单列表</h2>

    <!-- 查询 -->
    <el-form :inline="true" :model="searchObj" style="margin-bottom: 10px;">
      <el-form-item label="买家手机号">
        <el-input v-model="searchObj.buyerId" placeholder="请输入买家手机号" clearable/>
      </el-form-item>
      <el-form-item label="卖家手机号">
        <el-input v-model="searchObj.sellerId" placeholder="请输入卖家手机号" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
<!--        <el-button type="success" @click="showAddDialog">新增订单</el-button>-->
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="orderId" label="订单ID" width="100"/>
      <el-table-column prop="buyerId" label="买家手机号" width="100"/>
      <el-table-column prop="sellerId" label="卖家手机号" width="100"/>
      <el-table-column prop="productId" label="商品ID" width="100"/>
      <el-table-column prop="productName" label="商品名称" width="150"/>
      <el-table-column prop="price" label="单价" width="100"/>
      <el-table-column prop="quantity" label="数量" width="80"/>
      <el-table-column prop="totalPrice" label="总价" width="120"/>
      <el-table-column prop="ordersTime" label="下单时间" width="180"/>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200">
        <template #default="scope">
<!--          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>-->
          <el-button type="danger" size="small" @click="handleDelete(scope.row.orderId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :total="total"
        :page-sizes="[10,20,30,40]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
    />

    <!-- 编辑订单对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑订单" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="买家ID">
          <el-input v-model="editForm.buyerId"/>
        </el-form-item>
        <el-form-item label="卖家ID">
          <el-input v-model="editForm.sellerId"/>
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input v-model="editForm.productId"/>
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="editForm.quantity"/>
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="editForm.price"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancleEdit">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新增订单弹窗 -->
    <el-dialog v-model="addWinVisible" title="新增订单" width="500px">
      <el-form :model="newOrder" label-width="100px">
        <el-form-item label="买家ID">
          <el-input v-model="newOrder.buyerId" placeholder="请输入买家ID" />
        </el-form-item>
        <el-form-item label="卖家ID">
          <el-input v-model="newOrder.sellerId" placeholder="请输入卖家ID" />
        </el-form-item>
        <el-form-item label="商品ID">
          <el-input v-model="newOrder.productId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="newOrder.price" type="number" placeholder="请输入单价" />
        </el-form-item>
        <el-form-item label="数量">
          <el-input v-model="newOrder.quantity" type="number" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="总价">
          <el-input :value="totalPrice" disabled />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="addCancel">取消</el-button>
        <el-button type="primary" @click="addCommit">确定</el-button>
      </template>
    </el-dialog>

  </div>
</template>
<style scoped>
h2 {
  color: rgba(244, 64, 64, 0.35);
  margin-bottom: 20px;
}
</style>

